package com.newer.weatherforecast.ui;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.newer.weatherforecast.dao.CityDAO;
import com.newer.weatherforecast.dao.ConfigDAO;
import com.newer.weatherforecast.dao.SmsDAO;
import com.newer.weatherforecast.entity.CityInfo;
import com.newer.weatherforecast.entity.CurrentWeather;
import com.newer.weatherforecast.entity.ForecastWeather;
import com.newer.weatherforecast.entity.MyConfig;
import com.newer.weatherforecast.entity.SmsInfo;
import com.newer.weatherforecast.sms.SmsBroadCastReceiver;
import com.newer.weatherforecast.util.WeatherUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.SimpleExpandableListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class WeatherActivity extends Activity {
    private ViewPager vp_main = null;
    private List<View> mViewList = null;
    private static final int LEFT_SCREEN = 0,CENTRE_SCREEN = 1,RIGHT_SCREEN = 2;
    private static final int REFRESH_WHEATHER = 1,ADD_CITY = 2,SMS_INFO = 3,SET_CONFIG = 4;
    private static final int DELETE_SMS = 1 ,CLEAR_ALL = 2 ,HELP = 3,ABOUT = 4;
    private static final int SHOW_CITYINFO = 1,CITY_NOTFOUND = 2, LOGINSET = 3;
    private int choice_position = 0,city_choice_position = 0;
    private RelativeLayout re_widget_title = null,re_current_weather = null,re_forecast_weather1 = null,
    re_forecast_weather2 = null,re_forecast_weather3 = null,re_forecast_weather4 = null,re_widget_bottom = null,
	re_city_title = null,re_smsinfo_title = null;
    private TextView widget_city = null,widget_temp = null,widget_condition = null,
    widget_wind_direction = null,widget_wind_speed = null,widget_humidity = null,
    forcast_weather1_week = null,forcast_weather1_date = null,
    forcast_weather1_htemp = null,forcast_weather1_ltemp = null,forcast_weather2_week = null,
    forcast_weather2_date = null,forcast_weather2_htemp = null,forcast_weather2_ltemp = null,
    forcast_weather3_week = null,forcast_weather3_date = null,
    forcast_weather3_htemp = null,forcast_weather3_ltemp = null,forcast_weather4_week = null,
    forcast_weather4_date = null,forcast_weather4_htemp = null,forcast_weather4_ltemp = null,
    tv_widget_bottom = null,tvNull = null,tvLogin = null;
    private ImageView forcast_weather4_img = null,forcast_weather3_img = null,forcast_weather2_img = null,
    forcast_weather1_img = null,widget_img = null;
    private GridView grid_city = null;
    private View weatherView = null,addcity_view = null,smsView = null,cityView = null;
    private CurrentWeather currentWeather = null;
    private List<ForecastWeather> listForecastWeathers = null;
    private ConfigDAO configDAO = null;
    private CityDAO cityDAO = null;
    private SmsDAO smsDAO = null;
    private List<SmsInfo> smsInfo = null,childList = null;
    private EditText selectCity = null;
    private ListView select_list = null;
    private int reFreshTime = 0 ;
    private MyConfig myConfig = null;
    private CityInfo cityInfos[] = null;
    private CheckBox cbCloseTips = null;
    private WeatherUtil weatherUtil = null;
    private TimeThread mThread = null;
    private String requestCity = "";
    private TimeHandler timeHandler = new TimeHandler();
    private boolean isSetting = false ,isExit = false,configBack = false,isReset = false,loginOK = false;
    private SmsBroadCastReceiver receiver = null;
    private String qCityKey = "";
    private BroadcastReceiver refreshReceiver;
    private List<String> qCityList = null;
    private AlertDialog dialog;
    private SimpleAdapter cityadapter;
    private ArrayList<HashMap<String, Object>> cityItem;
    private ExpandableListView expandableListView = null;
    private List<Map <String, String>> groups = null;
    private List<Map <String, String>> child1 = null;
    private List<List <Map<String, String>>> childs = null;
    private String tips[] = {"Now Loading.","Now Loading..","Now Loading...","Now Loading...."};
	 SimpleExpandableListAdapter sadapter = null;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.loading);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        		WindowManager.LayoutParams.FLAG_FULLSCREEN);
        tvLogin = (TextView) findViewById(R.id.tvLogin);
        new MyAsycTask().execute("");
    }
    
    protected void onStart() {
    	super.onStart();
    	if(!configBack){
    		configBack = true;
    		return ;
    	}
    	System.out.println("进入Start");
    	myConfig = configDAO.QueryMyConfig();
    	if(myConfig.isAutoRefresh()){
    		if(reFreshTime!=myConfig.getRefreshFreq()){
    			isReset = true;
    			startAutoRefresh();
    		}
    	}else{
    		isReset = true;
    		if(mThread!=null){
    			try {
    				mThread.interrupt();
				} catch (Exception e) {
				}
			}
    	}
    }
    
    private void init(){
    	mViewList = new ArrayList<View>();
    	vp_main = (ViewPager) findViewById(R.id.weather_main);
    	getWeatherView();
    	getSmsView();
    	getCityView();
    	startInit();
    	mViewList.add(cityView);
    	mViewList.add(weatherView);
    	mViewList.add(smsView);
    	vp_main.setAdapter(new MyPager());
    	vp_main.setCurrentItem(CENTRE_SCREEN);
    }
 
    private void startInit(){
    	receiver = new SmsBroadCastReceiver();
    	IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
    	registerReceiver(receiver, filter);
    	refreshReceiver = new BroadcastReceiver() {
			public void onReceive(Context context, Intent intent) {
				refreshSmsInfo();
			}
		};
		IntentFilter refreshFileter = new IntentFilter("com.newer.list.doRefresh");
		registerReceiver(refreshReceiver, refreshFileter);
    	weatherUtil = new WeatherUtil();
    	configDAO = new ConfigDAO(WeatherActivity.this);
    	cityDAO = new CityDAO(getApplicationContext());
		myConfig = configDAO.QueryMyConfig();
		if(myConfig==null){
			isSetting = false;
		}else{
			isSetting = true;
			if(myConfig.isAutoRefresh()){
				startAutoRefresh();
			}
		}
		if(!isSetting||!configDAO.closeTips()){
			userTips();
		}
		showCity();
    }
    
    private void getWeatherView(){
    	weatherView = View.inflate(getApplicationContext(), R.layout.weather, null);
    	re_widget_title = (RelativeLayout) weatherView.findViewById(R.id.re_widget_title);
    	re_current_weather = (RelativeLayout) weatherView.findViewById(R.id.re_current_weather);
    	re_forecast_weather1 = (RelativeLayout) weatherView.findViewById(R.id.re_forcast_weather1);
    	re_forecast_weather2 = (RelativeLayout) weatherView.findViewById(R.id.re_forcast_weather2);
    	re_forecast_weather3 = (RelativeLayout) weatherView.findViewById(R.id.re_forcast_weather3);
    	re_forecast_weather4 = (RelativeLayout) weatherView.findViewById(R.id.re_forcast_weather4);
    	re_widget_bottom = (RelativeLayout) weatherView.findViewById(R.id.re_bottom);
    	widget_city = (TextView)weatherView.findViewById(R.id.widget_city);
    	widget_temp = (TextView)weatherView.findViewById(R.id.widget_temp);
    	widget_condition = (TextView)weatherView.findViewById(R.id.widget_condition);
        widget_wind_direction = (TextView)weatherView.findViewById(R.id.widget_wind_direction);
        widget_wind_speed = (TextView)weatherView.findViewById(R.id.widget_wind_speed);
        widget_humidity = (TextView)weatherView.findViewById(R.id.widget_humidity);
        widget_img = (ImageView) weatherView.findViewById(R.id.widget_img);
        forcast_weather1_week = (TextView)weatherView.findViewById(R.id.forcast_weather1_week);
        forcast_weather1_date = (TextView)weatherView.findViewById(R.id.forcast_weather1_date);
        forcast_weather1_htemp = (TextView)weatherView.findViewById(R.id.forcast_weather1_htemp);
        forcast_weather1_ltemp = (TextView)weatherView.findViewById(R.id.forcast_weather1_ltemp);
        forcast_weather2_week = (TextView)weatherView.findViewById(R.id.forcast_weather2_week);
        forcast_weather2_date = (TextView)weatherView.findViewById(R.id.forcast_weather2_date);
        forcast_weather2_htemp = (TextView)weatherView.findViewById(R.id.forcast_weather2_htemp);
        forcast_weather2_ltemp = (TextView)weatherView.findViewById(R.id.forcast_weather2_ltemp);
        forcast_weather3_week = (TextView)weatherView.findViewById(R.id.forcast_weather3_week);
        forcast_weather3_date = (TextView)weatherView.findViewById(R.id.forcast_weather3_date);
        forcast_weather3_htemp = (TextView)weatherView.findViewById(R.id.forcast_weather3_htemp);
        forcast_weather3_ltemp = (TextView)weatherView.findViewById(R.id.forcast_weather3_ltemp);
        forcast_weather4_week = (TextView)weatherView.findViewById(R.id.forcast_weather4_week);
        forcast_weather4_date = (TextView)weatherView.findViewById(R.id.forcast_weather4_date);
        forcast_weather4_htemp = (TextView)weatherView.findViewById(R.id.forcast_weather4_htemp);
        forcast_weather4_ltemp = (TextView)weatherView.findViewById(R.id.forcast_weather4_ltemp);
        tv_widget_bottom = (TextView)weatherView.findViewById(R.id.tv_widget_bottom);
        forcast_weather4_img = (ImageView) weatherView.findViewById(R.id.forcast_weather4_img);
        forcast_weather3_img = (ImageView) weatherView.findViewById(R.id.forcast_weather3_img);
        forcast_weather2_img = (ImageView) weatherView.findViewById(R.id.forcast_weather2_img);
        forcast_weather1_img = (ImageView) weatherView.findViewById(R.id.forcast_weather1_img);
        widget_img = (ImageView) weatherView.findViewById(R.id.widget_img);
    	re_widget_title.getBackground().setAlpha(80);
    	re_current_weather.getBackground().setAlpha(80);
    	re_forecast_weather1.getBackground().setAlpha(80);
    	re_forecast_weather2.getBackground().setAlpha(80);
    	re_forecast_weather3.getBackground().setAlpha(80);
    	re_forecast_weather4.getBackground().setAlpha(80);
    	re_widget_bottom.getBackground().setAlpha(80);
    	
    	re_current_weather.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				vp_main.setCurrentItem(LEFT_SCREEN);
			}
		});
    }
    
    private void getSmsView(){
    	smsView = View.inflate(getApplicationContext(), R.layout.smsinfo, null);
		re_smsinfo_title = (RelativeLayout) smsView.findViewById(R.id.re_smsinfo_title);
		expandableListView = (ExpandableListView) smsView.findViewById(R.id.sms_ex_lv);
		re_smsinfo_title.getBackground().setAlpha(80);
		expandableListView.setBackgroundResource(R.drawable.widget_bottom);
		expandableListView.getBackground().setAlpha(80);
		expandableListView.setCacheColorHint(0);
		expandableListView.setDivider(null);
		expandableListView.setGroupIndicator(getResources().getDrawable(R.drawable.expander_ic_folder));
    	tvNull = (TextView) smsView.findViewById(R.id.labels_null_tips);
    	refreshSmsInfo();
        expandableListView.setOnChildClickListener(new OnChildClickListener() {
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				choice_position = groupPosition;
				return false;
			}
		});
        expandableListView.setOnGroupClickListener(new OnGroupClickListener() {
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				choice_position = groupPosition;
				return false;
			}
		});
        
        expandableListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
				menu.add(1, DELETE_SMS, 1, "删除此人信息记录");
		    	menu.add(1, CLEAR_ALL, 2, "清空消息记录");
		    	menu.add(1, HELP, 3, "帮助");
		    	menu.add(1, ABOUT, 4, "关于");
			}
		});
    }
    
    public void refreshSmsInfo(){
    	smsInfo = new ArrayList<SmsInfo>();
    	childList = new ArrayList<SmsInfo>();
    	smsDAO = new SmsDAO(getApplicationContext());
    	groups = new ArrayList<Map<String,String>>(); 
        childs = new ArrayList<List<Map<String,String>>>();
    	smsInfo = smsDAO.queryAllSms();
    	if(smsInfo==null){
    		if(sadapter==null){
    			tvNull.setVisibility(View.VISIBLE);
        		return ;
    		}
    		child1.clear();
    	}else{
			tvNull.setVisibility(View.GONE);
    		for (int i = 0; i < smsInfo.size(); i++) {
    			System.out.println(smsInfo.size() + "   " + i + "   " + smsInfo.get(i).getSms_num());
    			Map<String , String> group1 = new HashMap<String , String>();
    			childList = smsDAO.queryByNum(smsInfo.get(i).getSms_num());
    			group1.put("who", smsInfo.get(i).getSms_name());
    			group1.put("count", childList.size()+"");
    			System.out.println(smsInfo.get(i).getSms_num());
    			if(childList==null){
    				System.out.println("查询出错");
    				return ;
    			}
    			child1 = new ArrayList<Map <String,String>>();
    			for (int j = 0; j < childList.size(); j++) {
    				Map<String , String> childdata1 = new HashMap<String , String>();
    				childdata1.put("body", childList.get(j).getSms_body());
    				childdata1.put("time", childList.get(j).getReceive_time());
    				childdata1.put("result", childList.get(j).getReturn_result());
    				child1.add(childdata1);
    			}
    			childs.add(child1);
    			groups.add(group1);
    		}
    	}
    	sadapter =
        	new SimpleExpandableListAdapter
        	(getApplicationContext(),groups,R.layout.smsgroup, 
        		new String[] { "who" ,"count"},new int[] { R.id.contact_num,R.id.request_num }, 
        			childs,R.layout.smschild,new String[] { "body","time","result" }, 
        				new int[] { R.id.tv_sms_body,R.id.tv_sms_time,R.id.return_result});        
        expandableListView.setAdapter(sadapter);
    }
    
    
    private void getCityView(){
    	cityView = View.inflate(getApplicationContext(), R.layout.city, null);
    	re_city_title = (RelativeLayout) cityView.findViewById(R.id.re_city_title);
    	re_city_title.getBackground().setAlpha(80);
    	grid_city = (GridView) cityView.findViewById(R.id.grid_city);
    	grid_city.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				cityDAO.clearCurrentCity();
				String cityname = cityItem.get(position).get(CityDAO.CITYINFO_NAME)+"";
				cityDAO.updateCurrentCity(position);
				isReset = true;
    			startAutoRefresh();
				vp_main.setCurrentItem(CENTRE_SCREEN);
				if(currentWeather==null){
					Toast.makeText(getApplicationContext(), "因网络故障,暂时无法刷新", Toast.LENGTH_SHORT).show();
					return;
				}
				String condition = currentWeather.getCondition();
				String temp = currentWeather.getTemp();
				int icon = weatherUtil.getWeatherImage(currentWeather.getIcon());
				Date date = new Date();
				String time = date.toLocaleString();
				String subTime = time.substring(time.indexOf("-")+1);
				System.out.println(subTime);
				CityInfo cityInfo = new CityInfo(cityname,true,subTime+"更新",temp,condition,icon);
				cityDAO.updateCityWeather(cityInfo,position);
				showCity();
			}
		});
    	grid_city.setOnItemLongClickListener(new OnItemLongClickListener() {

			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				city_choice_position = position;
				AlertDialog.Builder cityDialog = new Builder(WeatherActivity.this);
				cityDialog.setTitle("请选择你要使用的操作");
				cityDialog.setItems(new String[]{"删除城市","修改城市"}, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						switch (which) {
						case 1:
							long flag = cityDAO.delCityById(city_choice_position);
							if (flag>0) {
								Toast.makeText(getApplicationContext(), "删除城市成功", Toast.LENGTH_SHORT).show();
							}else {
								Toast.makeText(getApplicationContext(), "删除城市失败", Toast.LENGTH_SHORT).show();
							}
							break;
						case 2:
							Toast.makeText(getApplicationContext(), "时间关系,功能预留", Toast.LENGTH_SHORT).show();
							break;
						}
					}
				});
				cityDialog.create();
				return true;
			}
		});
    	grid_city.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			
			public void onCreateContextMenu(ContextMenu menu, View v,
					ContextMenuInfo menuInfo) {
			}
		});
    }
    
    public void addCity(){
    	dialog = new AlertDialog.Builder(WeatherActivity.this).create();
    	addcity_view = View.inflate(getApplicationContext(), R.layout.addcity, null);
    	dialog.setView(addcity_view);
    	selectCity = (EditText) addcity_view.findViewById(R.id.select_city);
    	select_list = (ListView) addcity_view.findViewById(R.id.city_list);
    	
    	selectCity.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				qCityKey = selectCity.getText().toString();
				if(qCityKey!=null&&!"".equals(qCityKey.trim())){
					qCityList = cityDAO.getSelectCity(qCityKey);
					ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,qCityList);
					select_list.setAdapter(adapter);
					select_list.setOnItemClickListener(new OnItemClickListener() {

						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {
							String addCityname = qCityList.get(position);
							String currentCity = cityDAO.getCurrentCityName();
							if (currentCity!=null&&!currentCity.equals("")) {
								cityDAO.clearCurrentCity();
							}
							CityInfo addCityInfo = new CityInfo(addCityname,true,"等待更新"," "," ",R.drawable.na);
							long flag = cityDAO.insertCity(addCityInfo);
							if(flag>0){
								showCity();
								dialog.dismiss();
								isReset = true;
				    			startAutoRefresh();
							}else {
								Toast.makeText(getApplicationContext(), "添加城市失败", Toast.LENGTH_SHORT).show();
							}
							
						}
					});
				}else {
					select_list.setAdapter(null);
				}
			}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			public void afterTextChanged(Editable s) {}
		});
    	dialog.show();
    }
    
    
    
    public void showCity(){
    	cityInfos = cityDAO.QueryMyCity();
    	if(cityInfos==null){
    		return;
    	}
    	cityItem = new ArrayList<HashMap<String, Object>>();  
    	for (int i = 0; i < cityInfos.length; i++) {
    		HashMap<String, Object> map = new HashMap<String, Object>();
    		map.put(CityDAO.CITYINFO_NAME, cityInfos[i].getCity_name());
    		if(cityInfos[i].isCurrent_city()){
    			map.put(CityDAO.CITYINFO_CURRENT_CITY, R.drawable.city_force);
    		}else {
    			map.put(CityDAO.CITYINFO_CURRENT_CITY, 0);
			}
    		map.put(CityDAO.CITYINFO_LAST_UPDATE_TIME, cityInfos[i].getLast_update_time());
    		map.put(CityDAO.CITYINFO_LAST_TEMPRETURE, cityInfos[i].getLast_tempreture());
    		map.put(CityDAO.CITYINFO_LAST_WEATHER, cityInfos[i].getLast_weather());
    		map.put(CityDAO.CITYINFO_LAST_ICON, cityInfos[i].getIcon());
    		cityItem.add(map);
		}
    	cityadapter = new SimpleAdapter(WeatherActivity.this, cityItem, R.layout.showcity,
    			new String[]{CityDAO.CITYINFO_NAME,CityDAO.CITYINFO_CURRENT_CITY,CityDAO.CITYINFO_LAST_UPDATE_TIME,
    			CityDAO.CITYINFO_LAST_TEMPRETURE,CityDAO.CITYINFO_LAST_WEATHER,CityDAO.CITYINFO_LAST_ICON},
    			new int[]{R.id.showcity_name,R.id.showcity_default_img,R.id.showcity_time,R.id.showcity_temp,R.id.showcity_condition,R.id.showcity_img});
    	cityadapter.notifyDataSetChanged();
    	grid_city.setAdapter(cityadapter);
    }
    
    
    
    
    public boolean onCreateOptionsMenu(Menu menu) {
    	menu.add(1, REFRESH_WHEATHER, 1, "刷新天气").setIcon(R.drawable.menu_update);
    	menu.add(1, ADD_CITY, 2, "添加城市").setIcon(R.drawable.menu_citymanage);
    	menu.add(1, SMS_INFO, 3, "信息管理").setIcon(R.drawable.menu_sharesetting);
    	menu.add(1, SET_CONFIG, 4, "系统设置").setIcon(R.drawable.menu_setting);
    	return super.onCreateOptionsMenu(menu);
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case REFRESH_WHEATHER:
    		vp_main.setCurrentItem(CENTRE_SCREEN);
    		startAutoRefresh();
    		if(currentWeather==null){
				Toast.makeText(getApplicationContext(), "因网络故障,暂时无法刷新", Toast.LENGTH_SHORT).show();
			}
    		break;
		case ADD_CITY:
			vp_main.setCurrentItem(LEFT_SCREEN);
			addCity();
			break;
		case SMS_INFO:
			vp_main.setCurrentItem(RIGHT_SCREEN);
			break;
		case SET_CONFIG:
			Intent intent = new Intent("ToMyConfig");
			intent.putExtra("type", 2);
			startActivity(intent);
			break;
		}
    	return super.onOptionsItemSelected(item);
    }
    
    
    public boolean onContextItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
		case DELETE_SMS:
			Log.e("position", smsInfo.get(choice_position)+"");
			smsDAO.deleteByNum(smsInfo.get(choice_position));
			refreshSmsInfo();
			break;
		case CLEAR_ALL:
			smsDAO.clearAll();
			refreshSmsInfo();
			break;
		case HELP:
			AlertDialog alertDialog = new AlertDialog.Builder(WeatherActivity.this).create();
			alertDialog.setTitle("帮助");
			View helpView = View.inflate(WeatherActivity.this, R.layout.help, null);
			cbCloseTips = (CheckBox) helpView.findViewById(R.id.cbTips);
			cbCloseTips.setVisibility(View.GONE);
			alertDialog.setView(helpView);
			alertDialog.setButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			alertDialog.show();
			break;
		case ABOUT:
			AlertDialog dialog = new AlertDialog.Builder(WeatherActivity.this).create();
			dialog.setTitle("关于");
			dialog.setMessage("110401MB" + "  第一小组 \n" + "组长:   " + "张鑫\n" + "组员:   " +"徐晓柏,彭毅,龙吉开,湛亮,李雪欣");
			dialog.setButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				}
			});
			dialog.show();
			break;
		}
    	return super.onContextItemSelected(item);
    }
    
    
    
    public String getCurrentCityName(){
    	if(cityDAO.getCurrentCityName()==null){
    		System.out.println("没拿到默认城市名字");
        	return "changsha";
    	}else{
    		return cityDAO.getCurrentCityName();
    	}
    }
    
    private void userTips(){
		AlertDialog alertDialog = new AlertDialog.Builder(WeatherActivity.this).create();
		View view = View.inflate(getApplicationContext(), R.layout.help, null);
		cbCloseTips = (CheckBox)view.findViewById(R.id.cbTips);
		alertDialog.setTitle("提示");
		alertDialog.setView(view);
		alertDialog.setButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
					if(isSetting){
						configDAO.updateCloseTips(cbCloseTips.isChecked());
					}else{
						configDAO.setCloseTips(cbCloseTips.isChecked());
						myConfig = configDAO.QueryMyConfig();
						firstTimeSetting();
					}
				}
		});
		alertDialog.show();
	}
    
    private void firstTimeSetting(){
		AlertDialog dialog = new AlertDialog.Builder(WeatherActivity.this).create();
		dialog.setTitle("提示");
		dialog.setMessage("系统检测到您是第一次使用，请完成系统设置");
		dialog.setButton("使用系统默认", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(cityDAO.getCurrentCity()==null){
					vp_main.setCurrentItem(LEFT_SCREEN);
					addCity();
					return;
				}
				startAutoRefresh();
			}
		});
		dialog.setButton2("点击自主设置", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Intent intent = new Intent("ToMyConfig");
				intent.putExtra("type", 1);
				startActivity(intent);
			}
		});
		dialog.show();
	}
    
    private void startAutoRefresh(){
		if(mThread!=null){
			try {
				mThread.interrupt();
			} catch (Exception e) {
			}
		}
    	mThread = new TimeThread();
    	reFreshTime = myConfig.getRefreshFreq();
    	mThread.start();
    }
    
    class TimeThread extends Thread{
    	public void run(){
    		while(true){
				try {
					if(isExit || isReset){
						isReset = false;
						break;
					}
//					requestCity = "changsha";
					requestCity = getCurrentCityName();
					if(requestCity==null){
						timeHandler.sendEmptyMessage(2);
						break;
					}
					URL url = new URL("http://www.google.com/ig/api?hl=zh_cn&weather=" + requestCity);
					weatherUtil.getCityWeather(url);
					currentWeather = weatherUtil.getCurrentWeather();
					if(currentWeather==null){
						continue;
					}
					listForecastWeathers = weatherUtil.getForecastWeathers();
					for (int i = 0; i < listForecastWeathers.size(); i++) {
						System.out.println(listForecastWeathers.get(i));
					}
					timeHandler.sendEmptyMessage(1);
					Thread.sleep(reFreshTime * 1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} catch (MalformedURLException e) {
					e.printStackTrace();
				}
			}
    	}
    }
    class TimeHandler extends Handler{	
    	public void handleMessage(Message msg) {
    		switch (msg.what) {
			case SHOW_CITYINFO:
				Date date = new Date();
    			String displayName = cityDAO.getZhCityName(currentWeather.getCity());
    			widget_city.setText(displayName);
    			widget_temp.setText(currentWeather.getTemp());
    			widget_condition.setText(currentWeather.getCondition());
    			widget_wind_direction.setText(currentWeather.getWind_direction());
    			widget_wind_speed.setText(currentWeather.getWind_speed());
    			widget_humidity.setText(currentWeather.getHumidity());
    			widget_img.setImageResource(weatherUtil.getWeatherImage(currentWeather.getIcon()));
    			forcast_weather1_week.setText(listForecastWeathers.get(0).getDay_of_week());
    			forcast_weather1_date.setText((date.getMonth() + 1)+"." + (date.getDate()+1));
    			forcast_weather1_htemp.setText(listForecastWeathers.get(0).getHigh_temp());
    			forcast_weather1_ltemp.setText(listForecastWeathers.get(0).getLow_temp());
    			forcast_weather2_week.setText(listForecastWeathers.get(1).getDay_of_week());
    			forcast_weather2_date.setText((date.getMonth() + 1) +"." + (date.getDate() + 2));
    			forcast_weather2_htemp.setText(listForecastWeathers.get(1).getHigh_temp());
    			forcast_weather2_ltemp.setText(listForecastWeathers.get(1).getLow_temp());
    			forcast_weather3_week.setText(listForecastWeathers.get(2).getDay_of_week());
    			forcast_weather3_date.setText((date.getMonth()+ 1) + "." + (date.getDate() + 3));
    			forcast_weather3_htemp.setText(listForecastWeathers.get(2).getHigh_temp());
    			forcast_weather3_ltemp.setText(listForecastWeathers.get(2).getLow_temp());
    			forcast_weather4_week.setText(listForecastWeathers.get(3).getDay_of_week());
    			forcast_weather4_date.setText((date.getMonth() + 1) +"." + (date.getDate() + 4));
    			forcast_weather4_htemp.setText(listForecastWeathers.get(3).getHigh_temp());
    			forcast_weather4_ltemp.setText(listForecastWeathers.get(3).getLow_temp());
    			tv_widget_bottom.setText(currentWeather.getCurrentDate());
    			forcast_weather4_img.setImageResource(weatherUtil.getWeatherImage(listForecastWeathers.get(3).getIcon()));
    			forcast_weather3_img.setImageResource(weatherUtil.getWeatherImage(listForecastWeathers.get(2).getIcon()));
    			forcast_weather2_img.setImageResource(weatherUtil.getWeatherImage(listForecastWeathers.get(1).getIcon()));
    			forcast_weather1_img.setImageResource(weatherUtil.getWeatherImage(listForecastWeathers.get(0).getIcon()));
    			widget_img.setImageResource(weatherUtil.getWeatherImage(currentWeather.getIcon()));
				break;
			case CITY_NOTFOUND:
				widget_city.setText("没有查询到默认城市，请点此设置");
    			widget_temp.setText("");
    			widget_condition.setText("");
    			widget_wind_direction.setText("");
    			widget_wind_speed.setText("");
    			widget_humidity.setText("");
				break;
			case LOGINSET:
				tvLogin.setText(tips[msg.arg1]);
				break;
			}
    		super.handleMessage(msg);
    	}
    }
    
    class MyAsycTask extends AsyncTask<String,String,String>{
		protected String doInBackground(String... params) {
			try {
				new LoginThread().start();  
				Thread.sleep(5000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			setContentView(R.layout.main);
			loginOK = true;
			init();
		}
	}
	class LoginThread extends Thread {
		public void run(){
			try {
				while(true){
					if(loginOK){
						break;
					}
					for (int i = 0; i < tips.length; i++) {
						Message msg = new Message();
						msg.what = LOGINSET;
						msg.arg1 = i;
						timeHandler.sendMessage(msg);
						Thread.sleep(800);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
    
    
    class MyPager extends PagerAdapter{
		public int getCount() {
			return mViewList.size();
		}

		public Object instantiateItem(View collection, int position) {
			((ViewPager) collection).addView(mViewList.get(position),0); 
			return mViewList.get(position);
		}

		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		public void restoreState(Parcelable state, ClassLoader loader) {
		}
		

		public Parcelable saveState() {
			
			return null;
		}

		public void startUpdate(View view) {
			
		}
		public void finishUpdate(View view) {
			
		}
		public void destroyItem(View collection, int position, Object view) {
			((ViewPager)collection).removeView(mViewList.get(position));
		}
    }
    
    protected void onDestroy() {
		super.onDestroy();
		isExit = true;
		configDAO.close();
		cityDAO.close();
		cityDAO.closeDatabase();
		smsDAO.close();
		unregisterReceiver(receiver);
		unregisterReceiver(refreshReceiver);
	}
    
}


